// pages/index/info_enrollment/info_enrollment.js
import {
  Alert,
  Toast,
  Confirm
} from 'wuss-weapp';
let app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    files: [],
    imagesUrls: [],
    formats: {},
    bottom: 0,
    readOnly: false,
    placeholder: '开始输入...',
    images: [],
    content:""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.setData({
      theme: app.globalData.theme,
      circleId: options.id,
      selectFile: this.selectFile.bind(this),
      uplaodFile: this.uplaodFile.bind(this),
    });
    app.setNavigationBarColor();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  /**
   * 选择图片
   */
  chooseImage: function(e) {
    wx.chooseImage({
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: res => {
        let tempFilePaths = res.tempFilePaths;
        this.setData({
          files: this.data.files.concat(res.tempFilePaths)
        });
      },
      fail: res => {}
    })
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  selectFile(files) {},
  uplaodFile(files) {
    return app.mpUploadFile(files);
  },
  uploadError(e) {},
  uploadSuccess(e) {
    console.error(e.detail.urls.length)
    e.detail.urls.forEach((item, index) => {
      this.data.imagesUrls.push(item);
    });
  },
  /**
   * 删除图片
   */
  deleteImg: function(e) {
    let url = e.detail.item.url;
    this.data.imagesUrls.forEach((item, index) => {
      if (item == url) {
        this.data.imagesUrls.splice(index, 1);
        this.setData({
          imagesUrls: this.data.imagesUrls
        });
        return;
      }
    });
  },
  /**
   * 富文本方法
   */
  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  onEditorReady() {
    wx.createSelectorQuery().select('#editor').context(res => {
      this.editorCtx = res.context
    }).exec()
  },

  undo() {
    this.editorCtx.undo()
  },
  redo() {
    this.editorCtx.redo()
  },
  format(e) {
    const {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },

  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    let that = this;
    this.editorCtx.clear({
      success(){
        that.setData({
          content:""
        });
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    wx.chooseImage({
      count: 6,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: resW => {
        for (let i = 0; i < resW.tempFilePaths.length; i++) {
          let progressUpdate = function (res) {
          };
          app.uploadFile(resW.tempFilePaths[i],progressUpdate).then(result=>{
            this.editorCtx.insertImage({
              src: result.data[0],
              width: '100%',
              success: function () {
              }
            })
          });
        }
      }
    })
  },
  /**
   * 提交
   */
  formSubmit: function(e) {
    this.editorCtx.getContents({
      success: res=> {
        this.setData({
          content:res.html
        });
      }
    })
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    let params = e.detail;
    if (!app.removeAllSpace(params.title)) {
      this.setData({
        error: "请输入标题"
      });
    } else if (!app.removeAllSpace(this.data.content)) {
      this.setData({
        error: "请输入内容"
      });
    } else if (this.data.imagesUrls.length == 0) {
      this.setData({
        error: "请上传封面"
      });
    } else {
      app.confirm('提示', '你确定要提交吗？').then(result => {
        wx.showLoading({
          title: '保存中...',
        })
        params["title"] = app.removeAllSpace(params.title);
        params["content"] = app.removeAllSpace(this.data.content).replace(/imgsrc/g, 'img src');
        params["circle_id"] = this.data.circleId;
        params["creator_id"] = app.globalData.userInfo["user_id"];
        params["creator_name"] = app.globalData.userInfo["name"];
        params["first_picture"] = this.data.imagesUrls[0];
        app.wxPostRequest("/circle/release", params).then(result => {
          prevPage.setData({
            isClickPublish:true
          });
          wx.navigateBack({
            delta: getCurrentPages()
          })
        });

      });
    }
  },
})